package com.fx.service.impl;

import cn.hutool.core.date.DateUtil;
import com.fx.entity.ChangeRecord;
import com.fx.entity.UserInfo;
import com.fx.entity.WalletInfo;
import com.fx.entity.WxPayConfig;
import com.fx.mapper.ChangeRecordMapper;
import com.fx.mapper.UserInfoMapper;
import com.fx.mapper.WalletInfoMapper;
import com.fx.service.WalletInfoService;
import com.fx.service.WxPayConfigService;
import com.fx.util.IdWorker;
import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.EntPayService;
import com.github.binarywang.wxpay.service.WxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class WalletInfoServiceImpl implements WalletInfoService {
    @Autowired
    private WalletInfoMapper walletInfoMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private WxPayConfigService wxPayConfigService;
    @Autowired
    private ChangeRecordMapper changeRecordMapper;
    @Autowired
    private IdWorker idWorker;

    @Override
    public WalletInfo getById(String flId) {
        return walletInfoMapper.getById(flId);
    }

    @Override
    public List<WalletInfo> getList(Map<String, Object> map) {
        return walletInfoMapper.queryList(map);
    }

    @Override
    public int getCount(Map<String, Object> map) {
        return walletInfoMapper.queryCount(map);
    }

    @Override
    public int save(WalletInfo walletInfo) {
        walletInfo.setFlId(String.valueOf(idWorker.nextId()));
        walletInfo.setFlCreatedTime(DateUtil.now());
        return walletInfoMapper.save(walletInfo);
    }

    @Override
    public int updateById(WalletInfo walletInfo) {
        return walletInfoMapper.updateById(walletInfo);
    }

    @Override
    public int remove(String flId) {
        return walletInfoMapper.remove(flId);
    }

    @Override
    public int batchRemove(String[] flIds) {
        return walletInfoMapper.batchRemove(flIds);
    }

    @Override
    public int withdrawByUserId(String userId, Double withdrawAmount, String name, String clientIp) throws WxPayException {
        Map<String,Object> param = new HashMap<String,Object>();
        int status = -1;
        String transferNo = "TRANSFER_NO_"+DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss:SSSS");
        WxPayConfig wxPayConfig = wxPayConfigService.getList(param).get(0);
        UserInfo userInfo = userInfoMapper.getById(userId);
        WalletInfo walletInfo = walletInfoMapper.getById(userInfo.getFlWallet());
        Double availableAmount = walletInfo.getFlAvailableAmount().doubleValue();
        if(withdrawAmount < availableAmount){
            return status;
        }
        EntPayService entPayService = wxPayService.getEntPayService();
        EntPayRequest entPayRequest = new EntPayRequest();
        entPayRequest.setAmount((int)(withdrawAmount*100));
        entPayRequest.setCheckName(name);
        entPayRequest.setOpenid(userInfo.getFlOpenId());
        entPayRequest.setMchAppid(wxPayConfig.getFlAppId());
        entPayRequest.setMchId(wxPayConfig.getFlMchId());
        entPayRequest.setNonceStr(String.valueOf(System.currentTimeMillis()));
        entPayRequest.setPartnerTradeNo(transferNo);
        entPayRequest.setReUserName(name);
        entPayRequest.setDescription("分润提现");
        entPayService.entPay(entPayRequest);
        entPayRequest.setSpbillCreateIp(clientIp);
        EntPayResult entPayResult = entPayService.entPay(entPayRequest);
        String resultCode = entPayResult.getResultCode();
        if("SUCCESS".equalsIgnoreCase(resultCode)){
            BigDecimal newAvailableAmount = BigDecimal.valueOf(walletInfo.getFlAvailableAmount().doubleValue() - withdrawAmount);
            BigDecimal newAvailableWithdrawAmount = BigDecimal.valueOf(walletInfo.getFlWithdrawAmount().doubleValue() - withdrawAmount);;
            walletInfo.setFlAvailableAmount(newAvailableAmount);
            walletInfo.setFlWithdrawAmount(newAvailableWithdrawAmount);
            walletInfoMapper.updateById(walletInfo);
            ChangeRecord changeRecord = new ChangeRecord();
            changeRecord.setFlId(String.valueOf(idWorker.nextId()));
            changeRecord.setFlChangeAmount(BigDecimal.valueOf(withdrawAmount));
            changeRecord.setFlChangeNo(transferNo);
            changeRecord.setFlChangeTime(DateUtil.now());
            changeRecord.setFlReason("分润提现");
            changeRecord.setFlStatus(1);
            changeRecord.setFlType(1);
            changeRecord.setFlUserId(userId);
            status = changeRecordMapper.save(changeRecord);
        }
        return status;
    }

    @Override
    public WalletInfo getCommissionInfo(String userId) {
        UserInfo userInfo = userInfoMapper.getById(userId);
        String walletId = userInfo.getFlWallet();
        WalletInfo walletInfo = walletInfoMapper.getById(walletId);
        return walletInfo;
    }


}
